﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using Microsoft.AspNet.SignalR;
using Newtonsoft.Json.Linq;
using r4u;
using r4u.business.logic.layer.ALERT;
using r4u.business.logic.layer.RECRUIT;
using r4u.data.access.layer;

namespace LinkedIn.Controllers
{
    public class AppliedController : Controller
    {
        //
        // GET: /Apply/
        //http://localhost:49832/Apply?code=AQQkDssxH6gIMo2KH3YKslSrXOXU4Wvz80aPpieBdiTJ9VMoIvv7F0AUipcaN6XyDRcDjmc3oLr-WiFwQsZTuxMpJXwEPYJSUIe9Z2CdmwQh1PBrELY&state=DCEEFWFwqe53sdffef424
        public ActionResult Index(string vacancy_id, string code, string state)
        {
            string URL = String.Format("https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code&code={0}&redirect_uri=http://localhost:49542/Applied?vacancy_id={1}&client_id=75nj2lib6zdk57&client_secret=VRa5rl4Oxhx5YEu8", code, vacancy_id);
            var client = new WebClient();
            var result = client.DownloadString(URL);
            dynamic data = JObject.Parse(result);
            string access_token = data.access_token;

            URL = String.Format("https://api.linkedin.com/v1/people/~:(id,first-name,last-name,projects,headline,num-connections,summary,honors-awards,specialties,picture-url,public-profile-url,email-address,educations,num-recommenders,recommendations-received,date-of-birth,location,skills,positions,interests,publications,certifications,courses,industry)?oauth2_access_token={0}", access_token);
            result = client.DownloadString(URL);

            XmlDocument profile = new XmlDocument();
            profile.LoadXml(result);
            Candidate candidate = new Candidate(profile);



            // All Checks
            Vacancy vacancy = new Vacancy();
            VACANCY v = vacancy.GetVacancyWithSkills(vacancy_id);
            var quota = 0;

            using (var context = new r4u.data.access.layer.r4uEntities())
            {
                quota = context.VACANCY_APPLICANT.Count(x => x.vacancy_id.Equals(vacancy_id));
            }


            if (DateTime.Now < v.valid_from)
            {
                ViewBag.error = String.Format ("Job vacancy has not yet been activated. Please try after {0}.", v.valid_from);
                return View("Error");
            }

            else if (DateTime.Now > v.valid_to)
            {
                ViewBag.error = "Sorry, the vacancy has been expired.";
                return View("Error");
            }

            else if (v.max_applications == quota)
            {
                ViewBag.error = "Sorry, the vacancy quota has been exceeded.";
                return View("Error");
            }


            if (!string.IsNullOrEmpty(v.allow_non_eligible) && v.allow_non_eligible.Equals("Y"))
            {
                if (vacancy.InsertApplicant(vacancy_id, profile))
                {
                    var myHub = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
                    myHub.Clients.All.addNewMessageToPage(v.vacancy_id, v.vacancy_for, candidate.FirstName + " " + candidate.LastName, candidate.Headline, candidate.PictureURL);

                    Mail m = new Mail();
                    m.SendApplicants(HttpContext.User.Identity.Name, vacancy_id);

                    ViewBag.error = "You have successfully applied for this job vacancy.";
                    return View("Success");
                }
                else
                {
                    ViewBag.error = "You have already applied for this job vacancy.";
                    return View("Error");
                }
            }
            else
            {
                bool isQualify = candidate.CheckQualify(vacancy_id);

                if (!isQualify)
                {
                    ViewBag.error = "Sorry, You are not eligible to apply for this vacancy based on your LinkedIn profile data.";
                    return View("Error");
                }
                else
                {
                    if (vacancy.InsertApplicant(vacancy_id, profile))
                    {
                        var myHub = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
                        myHub.Clients.All.addNewMessageToPage(v.vacancy_id, v.vacancy_for, candidate.FirstName + " " + candidate.LastName, candidate.Headline, candidate.PictureURL);

                        Mail m = new Mail();
                        m.SendApplicants(HttpContext.User.Identity.Name, vacancy_id);

                        ViewBag.error = "You have successfully applied for this job vacancy.";
                        return View("Success");
                    }
                    else
                    {
                        ViewBag.error = "You have already applied for this job vacancy.";
                        return View("Error");
                    }
                }

            }

            ViewBag.error = "Error occured.";
            return View("Error");
        }

    }
}
